# Direct outputs eligible for public release

# GLOBAL SETTINGS --------------------------------------------------------------

options(
  scipen = 999,
  digits = 16,
  max.print = .Machine$integer.max,
  show.error.locations = TRUE,
  warn = 1
)

RNGkind("L'Ecuyer-CMRG")
seed <- 818675309L
set.seed(seed) # setting main seed

# PACKAGES ---------------------------------------------------------------------

library(data.table)

# PACKAGE SETTINGS -------------------------------------------------------------

# data.table
setDTthreads(threads = 1)
options(datatable.print.class = TRUE, datatable.print.keys = TRUE)
# so that printing the data.table also shows the variable type on top

# BEGIN FILE -------------------------------------------------------------------

# Just in case something masks 'source()', use extra deliberate base::source().
base::source("~/code/0-utility-functions/table-and-text-utils.R", local = TRUE)

# READ IN OUR DATA -------------------------------------------------------------

# Focus on the aggregate (+1 to +5) estimates (event_time == 99) throughout

new_marriage_dt <-
    readRDS(
        "~/estimation-output/unearned_income_effect_estimates_new_marriage.rds" #nolint
    )
setnames(new_marriage_dt, "ref_event_time", "event_time")
new_marriage_dt <- new_marriage_dt[event_time == 99]

divorce_dt <-
    readRDS(
        "~/estimation-output/unearned_income_effect_estimates_divorce.rds" #nolint
    )
setnames(divorce_dt, "ref_event_time", "event_time")
divorce_dt <-
    divorce_dt[event_time == 99]

up_job_to_job_dt <-
    readRDS(
        "~/estimation-output/unearned_income_effect_estimates_firm_move_up.rds" #nolint
    )
setnames(up_job_to_job_dt, "ref_event_time", "event_time")
up_job_to_job_dt <-
    up_job_to_job_dt[event_time == 99]

# MAKE TABLE -------------------------------------------------------------------

filedir <- "~/paper/tables/table-A.13.tex"
file.create(filedir)

# Start Table A.13
start_latex_table(
    column_structure = "ccccccc",
    file_dir = filedir,
    append = TRUE
)
add_latex_table_rule(rule_type = "toprule", file_dir = filedir, append = TRUE)
add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)

heading_text_input1 <-
    " &  &  & \\multicolumn{4}{c}{Sample} "
write_latex_table_row(heading_text_input1, file_dir = filedir, append = TRUE)

add_latex_cmidrule(
    point_start_col = "l",
    point_end_col = "r",
    start_col = 4,
    end_col = 7,
    file_dir = filedir,
    append = TRUE
)

heading_text_input2 <-
    " \\multirow{3}{*}{Outcome} & \\multirow{3}{*}{Value} & & \\multirow{2}{*}{Full Sample} & & Quartile 1  &  Quartile 4 " #nolint
write_latex_table_row(heading_text_input2, file_dir = filedir, append = TRUE)

heading_text_input3 <-
    "  & & & & & Pre-Win Income  &  Pre-Win Income "
write_latex_table_row(heading_text_input3, file_dir = filedir, append = TRUE)

heading_text_input4 <-
    "  & & & (1) & & (2)  &  (3) "
write_latex_table_row(heading_text_input4, file_dir = filedir, append = TRUE)

heading_text_input1 <- NULL
heading_text_input2 <- NULL
heading_text_input3 <- NULL
heading_text_input4 <- NULL
rm(
    heading_text_input1,
    heading_text_input2,
    heading_text_input3,
    heading_text_input4
)

add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Add body of Table A.13
# - introduce convenience functions given a similar structure throughout

TableA13Row1 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            "\\multirow{4}{*}{%s} & Estimate & & %s & & %s & %s",
            text,
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 5]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 1]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 4]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

TableA13Row2 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & Standard Error & & (%s) & & (%s) & (%s)",
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 5]$cluster_se, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 1]$cluster_se, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 4]$cluster_se, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

TableA13Row3 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & Counterfactual Mean & & %s & & %s & %s",
            fmt_fixed_decimal(
                input = dt_temp[model == "counterfactual_mean" & income_quartile == 5]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 2,
                decimal_digits = 2,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "counterfactual_mean" & income_quartile == 1]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 2,
                decimal_digits = 2,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "counterfactual_mean" & income_quartile == 4]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 2,
                decimal_digits = 2,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

TableA13Row4 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & Percentage Change & & %s & & %s & %s",
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 5]$estimate / dt_temp[model == "counterfactual_mean" & income_quartile == 5]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 1,
                decimal_digits = 1,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 1]$estimate / dt_temp[model == "counterfactual_mean" & income_quartile == 1]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 1,
                decimal_digits = 1,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 4]$estimate / dt_temp[model == "counterfactual_mean" & income_quartile == 4]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 1,
                decimal_digits = 1,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}


# New Marriage
TableA13Row1(
    dt = new_marriage_dt,
    text = "New Marriage",
    scaler = 10000
)
TableA13Row2(
    dt = new_marriage_dt,
    scaler = 10000
)
TableA13Row3(
    dt = new_marriage_dt,
    scaler = 1
)
TableA13Row4(
    dt = new_marriage_dt,
    scaler = 1000000
)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Divorce
TableA13Row1(
    dt = divorce_dt,
    text = "Divorce",
    scaler = 10000
)
TableA13Row2(
    dt = divorce_dt,
    scaler = 10000
)
TableA13Row3(
    dt = divorce_dt,
    scaler = 1
)
TableA13Row4(
    dt = divorce_dt,
    scaler = 1000000
)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# End Table A.13
add_latex_table_rule(
  rule_type = "bottomrule",
  file_dir = filedir,
  append = TRUE
)
end_latex_table(file_dir = filedir, append = TRUE)
filedir <- NULL
rm(filedir)

# Housekeeping
new_marriage_dt <- NULL
divorce_dt <- NULL
rm(new_marriage_dt, divorce_dt)